package com.yusvn.scm.goods.buhuo.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.yitter.idgen.YitIdHelper;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.constant.Const;
import com.yusvn.scm.common.kit.RetKit;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 门店补货
 *
 * @author liugz
 */
public class ScmBuhuoMdbhService extends BaseService {

    /**
     * 定时同步数据 计算补货数据
     */
    public RetKit addDataBhsp() {
        try {
            //调用计算所有门店补货方法
            symdbh();

            //新增补货临时表， 用于解决界面查询数据慢
        	ThreadUtil.execute(() -> addDataDks()); //异步执行，加快速度
        	ThreadUtil.execute(() -> addDataKs());  //异步执行，加快速度
        } catch (Exception e) {
            e.printStackTrace();
            return RetKit.fail("计算补货 失败");
        }
        return RetKit.ok("计算补货 成功");
    }

    /**
     * 表1 获取查询数据到中间表 店款色
     */
    public RetKit addDataDks() {
    	Kv kv = Kv.create().set("cid", getCid());
    	kv.set(selectPz()); //商品属性动态字段

    	try {
        	//店款色的查询数据
            Db.use(Const.SCMDB).update("truncate table scm_buhuo_data_dks");
        	Db.use(Const.SCMDB).template("scmBuhuoJob.addDataDks", kv).update();
		} catch (Exception e) {
			e.printStackTrace();
			return RetKit.ok("新增补货临时数据失败");
		}

        return RetKit.ok("新增补货临时数据成功");
    }

    /**
     * 表1 获取查询数据到中间表 款色
     */
    public RetKit addDataKs() {
    	Kv kv = Kv.create().set("cid", getCid());
    	kv.set(selectPz()); //商品属性动态字段

    	try {
        	//款色的查询数据
            Db.use(Const.SCMDB).update("truncate table scm_buhuo_data_ks");
        	Db.use(Const.SCMDB).template("scmBuhuoJob.addDataKs", kv).update();
		} catch (Exception e) {
			e.printStackTrace();
			return RetKit.ok("新增补货临时数据失败2");
		}

        return RetKit.ok("新增补货临时数据成功2");
    }


    /**
     * 获取商品动态属性对应表
     * @return
     */
    public List<Record> selectAllAttrib() {
        List<Record> records = Db.use(Const.SCMDB).find("select a.pzmx1 as dtzd, b.id as id, b.attribdef as attribdef, b.attribdefname " +
        		"from (" +
        		"  select * from scm_pzbhmx where mid=(select id from SCM_PZBH where bh='scm_buhuo_dtzd') " +
        		") a " +
        		"inner join (" +
        		"  select id, 'attrib'||to_number(attribdef) as dtzderp, attribdef, attribdefname from defattribdef where isallow=1 and cid=? " +
        		") b on a.pzmx2=b.dtzderp "
        		+ "", getCid());

        return records;
    }

    /**
     * 获取某个商品属性
     * @param kv
     * @return
     */
    public List<Record> selctAttribById(Kv kv) {
        List<Record> records = Db.use(Const.SCMDB).find("select * from defattrib where attribdefid = ? and  cid = ?", kv.get("attr"), getCid());

        return records;
    }

    /**
     * 计算 所有门店补货
     */
    public RetKit symdbh() {
//		System.out.println("开始自动补货:"+DateUtil.date(System.currentTimeMillis()));
        //将参数放入kv中，便于后续使用
        Kv kv = Kv.create();

        //当前操作用户 默认系统操作
        String userid = "0";
        String cid = getCid();
        kv.set("cid", cid);
        kv.set("userid", userid);

        //先清空所有补货数据
        Db.use(Const.SCMDB).update("truncate table scm_buhuo_mdbhjgmx"); //补货明细表
        Db.use(Const.SCMDB).update("truncate table scm_buhuo_mdbhjg"); //补货主表

        //一、取数
        //获取商品属性 (用于动态获取商品属性id)
        List<Record> spsxList = Db.use(Const.SCMDB).find("select id, ATTRIBCODE as code, 'attrib'||attribno as attribno from DEFATTRIB where cid=? ", cid); //LPAD(attribno,2,'0')
        //设置商品属性定义编号对应的字段
        Kv spdtsx = Kv.create();
        for (int i = 1; i <= 20; i++) {
            spdtsx.set(String.format("%02d", i), "attrib" + i);
        }

        //先获取补货配置参数并解析
        List<Record> pzList = Db.use(Const.SCMDB).find("select id, mc, bh, pz1, pz2, pz3, pz4, pz5, pz6, seq from SCM_PZBH ");
        List<Record> pzmxList = Db.use(Const.SCMDB).find("select b.id, b.mid, b.pzmx1, b.pzmx2, b.pzmx3, b.pzmx4, b.pzmx5, b.pzmx6, b.seq as mxseq "
                + ", a.bh, a.pz1, a.pz2, a.pz3, a.pz4, a.pz5, a.pz6 "
                + "from SCM_PZBHMX b "
                + "left join SCM_PZBH a on b.MID=a.id "
                + "order by a.seq, a.id, b.seq, b.id ");

        //动态字段对应表 scm_buhuo_dtzd
        //List<Record> dtzdList = pzmxList.stream().filter(r->r.getStr("bh").equals("scm_buhuo_dtzd")).collect(Collectors.toList());

        //补货规则列表
        List<Record> bhgzList = pzmxList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_bhgz")).collect(Collectors.toList());
        //补货规则属性对照表
        List<Record> bhgzsxList = pzmxList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_bhgzsx")).collect(Collectors.toList());

        //商品停补属性对照表
        Record sptbsx = pzList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_sptbsx")).findFirst().get();
        //商品正价属性对照表
        Record spzjsx = pzList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_spzjsx")).findFirst().get();
        //商品特价属性对照表
        Record sptjsx = pzList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_sptjsx")).findFirst().get();
        //商品均码对照表
        Record spjm = pzList.stream().filter(r -> r.getStr("bh").equals("scm_buhuo_spjm")).findFirst().get();

        //是否排除促销商品 (0表示否、1表示是)
        String cs_pccx = pzmxList.stream().filter(r -> (r.getStr("bh").equals("scm_buhuo_pcgz") && r.getStr("pzmx1").equals("scm_buhuo_pccx")))
                .findFirst().get().getStr("pzmx3");
        //是否排除停补商品 (0表示否、1表示是)
        String cs_pctb = pzmxList.stream().filter(r -> (r.getStr("bh").equals("scm_buhuo_pcgz") && r.getStr("pzmx1").equals("scm_buhuo_pctb")))
                .findFirst().get().getStr("pzmx3");
        //某款色总采退数量大于等于X件则不补货
        Integer cs_pcth = pzmxList.stream().filter(r -> (r.getStr("bh").equals("scm_buhuo_pcgz") && r.getStr("pzmx1").equals("scm_buhuo_pcth")))
                .findFirst().get().getInt("pzmx3");

        String cs_sptbsx = spdtsx.getStr(sptbsx.getStr("pz1")) == null ? sptbsx.getStr("pz1") : spdtsx.getStr(sptbsx.getStr("pz1")); //商品停补属性字段
        String cs_sptbsxV = spsxList.stream().filter(r -> r.getStr("attribno").equals(cs_sptbsx) && r.getStr("code").equals(sptbsx.getStr("pz2"))).findFirst().get().getStr("id"); //sptbsx.getStr("pz2");
        String cs_spzjsx = spdtsx.getStr(spzjsx.getStr("pz1")) == null ? spzjsx.getStr("pz1") : spdtsx.getStr(spzjsx.getStr("pz1")); //商品正价属性字段
        String cs_spzjsxV = spsxList.stream().filter(r -> r.getStr("attribno").equals(cs_spzjsx) && r.getStr("code").equals(spzjsx.getStr("pz2"))).findFirst().get().getStr("id"); //spzjsx.getStr("pz2");
        String cs_sptjsx = spdtsx.getStr(sptjsx.getStr("pz1")) == null ? sptjsx.getStr("pz1") : spdtsx.getStr(sptjsx.getStr("pz1")); //商品特价属性字段
        String cs_sptjsxV = spsxList.stream().filter(r -> r.getStr("attribno").equals(cs_sptjsx) && r.getStr("code").equals(sptjsx.getStr("pz2"))).findFirst().get().getStr("id"); //sptjsx.getStr("pz2");
        String cs_spjm = spjm.getStr("pz1"); //商品均码

        //将参数放入kv中，便于后续使用
        kv.set("cs_sptbsx", cs_sptbsx);     //商品停补属性字段
        kv.set("cs_sptbsxV", cs_sptbsxV);   //商品停补属性的值
        kv.set("cs_spzjsx", cs_spzjsx);     //商品正价属性字段
        kv.set("cs_spzjsxV", cs_spzjsxV);   //商品正价属性的值
        kv.set("cs_sptjsx", cs_sptjsx);     //商品特价属性字段
        kv.set("cs_sptjsxV", cs_sptjsxV);   //商品特价属性的值
        kv.set("cs_spjm", cs_spjm);         //商品均码组编号
        kv.set("cs_pccx", cs_pccx);     //促销商品是否参与补货
        kv.set("cs_pctb", cs_pctb);     //停补商品是否参与补货
        kv.set("cs_pcth", cs_pcth);     //某款色总采退数量大于等于X件则不补货

        //获取补货门店
        List<Record> mdList = Db.use(Const.SCMDB).template("scmBuhuoJob.store", kv).find();

        //二、运算
        //循环补货策略列表
        for (Record bhgz : bhgzList) {
            String bhgzBh = bhgz.getStr("pzmx1"); //补货规则编号
            String sqlWhere = ""; //动态查询条件
//			System.out.println("补货规则:"+bhgzBh+" "+DateUtil.date(System.currentTimeMillis()));

            //获取补货规则明细
            List<Record> bhgzmxList = pzmxList.stream().filter(r -> r.getStr("bh").equals(bhgzBh)).collect(Collectors.toList());

            //判断正价特价并设置参数 为了拼接sql查询条件
            String ztj = bhgz.getStr("pzmx2");
            if ("1".equals(ztj)) { //特价
                sqlWhere = sqlWhere + " and " + cs_sptjsx + " = " + cs_sptjsxV + " ";
            } else { //正价
                sqlWhere = sqlWhere + " and " + cs_spzjsx + " = " + cs_spzjsxV + " ";
            }

            //获取补货规则明细对应的商品属性 （为了拼接sql查询条件）
            List<Record> bhgzsxmxList = bhgzsxList.stream().filter(r -> r.getStr("pzmx1").equals(bhgzBh)).collect(Collectors.toList());
            Map<String, String> kvSxdy = new HashMap<>();  //以组合关系组暂存
            for (Record sxmx : bhgzsxmxList) {
                //商品属性定义
                String spsxdy = spdtsx.getStr(sxmx.getStr("pzmx2")) == null ? sxmx.getStr("pzmx2") : spdtsx.getStr(sxmx.getStr("pzmx2")); //商品属性定义字段
                String ysgx = sxmx.getStr("pzmx3"); //运算关系 =、<>
                String spsx = spsxList.stream().filter(r -> r.getStr("attribno").equals(spsxdy) && r.getStr("code").equals(sxmx.getStr("pzmx4"))).findFirst().get().getStr("id"); //sxmx.getStr("pzmx4"); //商品属性值
                String ljgx = sxmx.getStr("pzmx5"); //逻辑关系 and、or
                String zhgx = sxmx.getStr("pzmx6"); //组合关系 1、2、3...
                //根据属性定义拼接sql查询条件，并以组合关系为key暂存到map
                kvSxdy.put(zhgx,
                        (StrKit.isBlank(kvSxdy.get(zhgx)) ? "" : (kvSxdy.get(zhgx) + " " + ljgx)) + " " + spsxdy + " " + ysgx + " " + spsx + " "
                );
            }
            //循环暂存的map，以组合关系为1组、拼接sql查询条件
            for (String key : kvSxdy.keySet()) {
                sqlWhere = sqlWhere + " and (" + kvSxdy.get(key) + ") ";
            }
            kv.set("cs_sqlwhere", sqlWhere);
            //System.out.println("sqlWhere:"+sqlWhere);

            //循环补货门店
            for (Record md : mdList) {
                kv.set("cs_mdid", md.get("id")); //用于过滤门店
//                System.out.println("门店:"+md);

                //暂存补货结果的集合
                List<Record> bhjgList = new ArrayList<Record>();

                //循环补货规则明细
                for (Record gzmx : bhgzmxList) {
//                	System.out.println("补货规则明细:"+gzmx);
                    Integer cs_lsts = StrKit.isBlank(gzmx.get("pzmx1")) ? 0 : gzmx.getInt("pzmx1");      //近{值1}天
                    Integer cs_sql = StrKit.isBlank(gzmx.get("pzmx2")) ? 0 : gzmx.getInt("pzmx2");       //售罄率大于等于{值2}
                    Integer cs_bhsl = StrKit.isBlank(gzmx.get("pzmx3")) ? 1 : gzmx.getInt("pzmx3");      //补货数量{值3}
                    Integer cs_bhsx = StrKit.isBlank(gzmx.get("pzmx4")) ? 9999 : gzmx.getInt("pzmx4");      //补货数量上限{值4}
                    Integer cs_bhsxjm = StrKit.isBlank(gzmx.get("pzmx5")) ? 9999 : gzmx.getInt("pzmx5");    //均码补货数量上限{值5}
                    String bhtj = gzmx.getStr("pzmx6");       //补货条件{值6} （均码、整手）

                    //将补货规则明细参数放入kv，用于动态组装sql条件值
                    kv.set("cs_lsts", cs_lsts);
                    kv.set("cs_sql", cs_sql);
                    kv.set("cs_bhsl", cs_bhsl);
                    kv.set("cs_bhsx", cs_bhsx);
                    kv.set("cs_bhsxjm", cs_bhsxjm);
                    kv.set("cs_bhtj", bhtj);

                    //获取当前门店需补货的商品
                    List<Record> xbhspList = Db.use(Const.SCMDB).template("scmBuhuoJob.getBhqs", kv).find();
                    if (xbhspList == null || xbhspList.size() <= 0) {
                        continue;
                    }

                    String bz = ""; //补货备注  后期解析 TODO

                    //计算补货
                    for (Record xbhsp : xbhspList) {
                        //判断当前需补货商品是否已经存在 暂存补货结果集 中， 存在则不计算当前门店商品的补货
                        Long isCount = bhjgList.stream().filter(r -> r.getStr("mdid").equals(xbhsp.getStr("mdid")) && r.getStr("skuid").equals(xbhsp.getStr("skuid"))).count();
                        if (isCount > 0) {
                            continue;
                        }

                        int bhsl = 0; //补货数量
                        int bhslsx = cs_bhsx; //补货数量上限

                        //判断商品是否为均码，调整补货数量上限
                        if (cs_spjm.equals(xbhsp.getStr("cmzbh"))) {   //if("均码".equals(bhtj)) {}
                            bhslsx = cs_bhsxjm;
                        }

                        //默认补货数量为零售数量*补货倍数（销1补几）
                        bhsl = cs_bhsl * xbhsp.getInt("lssl");

                        //整手补（即当前款色每个尺码补几件）
                        if ("整手".equals(bhtj)) {
                            bhsl = cs_bhsl;
                        }

                        //补货数量不能超上限
                        if (bhsl > bhslsx) {
                            bhsl = bhslsx;
                        }

                        //需补货数量大于0才补货
                        if (bhsl <= 0) {
                            continue;
                        }

                        //新增一条补货数据到暂存补货集合中
                        Record bhspRec = new Record();
                        bhspRec.set("spid", xbhsp.get("spid")); //商品ID
                        bhspRec.set("ysid", xbhsp.get("ysid")); //颜色ID
                        bhspRec.set("cmid", xbhsp.get("cmid")); //尺码ID
                        bhspRec.set("skuid", xbhsp.get("skuid")); //SKUID
                        bhspRec.set("mdid", xbhsp.get("mdid")); //门店ID
                        bhspRec.set("jybhsl", bhsl); //建议补货数量
                        bhspRec.set("sjbhsl", bhsl); //实际补货数量
                        bhspRec.set("bz", bz); //补货备注说明
                        bhspRec.set("ppid", xbhsp.get("ppid")); //商品品牌区域ID

                        bhjgList.add(bhspRec); //将当前行补货明细暂存到补货结果集
                        bhspRec = null;
                    }
//                    System.out.println(" bhjgList:"+bhjgList.size());
                }

                //三、写入结果
                //批量将补货数据写入补货结果表
                if (bhjgList.size() > 0) {
                    Object[][] paras = new Object[bhjgList.size()][10];
                    for (int i = 0; i < bhjgList.size(); i++) {
                        paras[i][0] = YitIdHelper.nextId();          //唯一ID(雪花漂移)
                        paras[i][1] = bhjgList.get(i).get("spid");   //商品ID
                        paras[i][2] = bhjgList.get(i).get("ysid");   //颜色ID
                        paras[i][3] = bhjgList.get(i).get("cmid");   //尺码ID
                        paras[i][4] = bhjgList.get(i).get("skuid");  //SKUID
                        paras[i][5] = bhjgList.get(i).get("mdid"); //补货门店ID
                        paras[i][6] = bhjgList.get(i).get("jybhsl"); //建议补货数量
                        paras[i][7] = bhjgList.get(i).get("sjbhsl"); //实际补货数量
                        paras[i][8] = bhjgList.get(i).get("bz");     //备注
                        paras[i][9] = bhjgList.get(i).get("ppid");   //商品品牌区域ID
                    }
                    Db.use(Const.SCMDB).batch("insert into scm_buhuo_mdbhjgmx(id, spid, ysid, cmid, skuid,  mdid, jybhsl, sjbhsl, bz, ppid) "
                            + "values(?,?,?,?,?, ?,?,?,?,?) ", paras, 1000);
                }
                //清空补货结果暂存集合
                bhjgList = null;
            }

        }

        //将补货明细表数据汇总生成到补货主表
        addBhzb();

//		System.out.println("结束自动补货:"+DateUtil.date(System.currentTimeMillis()));
        return RetKit.ok();
    }

    /**
     * 将补货明细表数据汇总生成到补货主表
     * @return
     */
    public RetKit addBhzb() {
    	//按店品牌汇总补货结果明细
    	List<Record> recList = Db.use(Const.SCMDB).find("select a.mdid, a.ppid, min(a.createtime) as bhrq, sum(jybhsl) as jybhsl, sum(sjbhsl) as sjbhsl "
    			+ "from SCM_BUHUO_MDBHJGMX a group by a.mdid, a.ppid ");
    	//批量新增
    	Object[][] paras = new Object[recList.size()][4];
		for(int i=0;i<recList.size();i++) {
			paras[i][0] = YitIdHelper.nextId();
			paras[i][1] = recList.get(i).get("mdid");
			paras[i][2] = recList.get(i).get("ppid");
			paras[i][3] = recList.get(i).get("bhrq");
		}

		int[] cntArr = Db.use(Const.SCMDB).batch("insert into scm_buhuo_mdbhjg(id, mdid, ppid, bhrq) values(?,?,?,?) ", paras, 100);

		if(cntArr.length>0) {
			return RetKit.ok("成功");
		}

		return RetKit.fail("失败");
    }

    /**
     * 表1 获取门店补货商品
     */
    public List<Record> getMdbhsp(Kv kv) {
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", getSsmdqx(kv.getStr("userCode"))); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        kv.set("goodsimg", getGoodsimg()); //商品图片地址
        return Db.use(Const.SCMDB).template("scmBuhuoMdbh.getMdbhsp", kv).find();
    }

    /**
     * 获取某个商品的颜色尺码，用于新增
     */
    public List<Record> getSpyscm(Kv kv) {
        kv.set("cid", getCid());

        return Db.use(Const.SCMDB).template("scmBuhuoMdbh.getSpyscm", kv).find();
    }

    /**
     * 获取本次补货明细
     */
    public List<Record> getMdbhmx(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        // 查询结果到页面
        List<Record> recPage = Db.use(Const.SCMDB).template("scmBuhuoMdbh.getMdbhmx", kv).find();
        return recPage;
    }

    /**
     * 获取某个商品补货数据， 用于修改补货数量
     * @param kv
     * @return
     */
    public List<Record> getBhJybh(Kv kv) {
        kv.set("cid", getCid());
        List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoMdbh.getBhJybh", kv).find();
        return records;
    }

    /**
     * 新增补货商品
     */
    public RetKit insertMdbh(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
        	return sftj;
        }
        //判断是否存在
        System.out.println("kv"+kv);
        int cnt = Db.use(Const.SCMDB).queryInt("select count(*) from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=?"
        		, mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        if(cnt<=0) {
        	//获取商品信息
        	Record rec = Db.use(Const.SCMDB).findFirst("select sku.id as skuid, sp.ATTRIB1 as ppid  " +
        			"from defsku sku " +
        			"left join DEFSTYLE sp on sku.STYLEID=sp.ID " +
        			"where sku.cid=? and sku.STYLEID=? and sku.clrid=? and sku.sizeid = ?"
        			, kv.get("cid"), kv.get("spid"), kv.get("ysid"),kv.get("cmid") );
        	//新增
        	Db.use(Const.SCMDB).update("insert into scm_buhuo_mdbhjgmx(id, mdid, spid, ysid, cmid,  skuid, ppid, jybhsl, sjbhsl, sjzt, mdqr) "
        			+ "values(?,?,?,?,?, ?,?,?,?,?,?) "
        			,YitIdHelper.nextId(), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid")
        			, rec.get("skuid"), rec.get("ppid"), 0, kv.get("sjbhsl"), 2, 1);
        }else {
            Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjgmx set mdsc=0, sjbhsl = ?, mdqr=1, sjzt=2 where mdid=? and spid=? and ysid=? and cmid = ? "
                    ,kv.get("sjbhsl"), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));
            return RetKit.fail("修改成功");
        }

        return RetKit.ok("新增成功");
    }

    /**
     * 修改门店补货
     *
     * @param kv
     * @return
     */
    public RetKit upudateBhjg(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
        	return sftj;
        }

        //判断需补货数据在补货结果明细表中是否存在 (查询原实际补货数量)
        Integer cnt = Db.use(Const.SCMDB).queryInt("select count(1) as cnt from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=? "
        		, mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        if(null==cnt || 0 >= cnt) { // || cnt<=0
        	//获取商品信息
        	Record rec = Db.use(Const.SCMDB).findFirst("select sku.id as skuid, sp.ATTRIB1 as ppid  " +
        			"from defsku sku " +
        			"left join DEFSTYLE sp on sku.STYLEID=sp.ID " +
        			"where sku.cid=? and sku.STYLEID=? and sku.clrid=? and sku.sizeid = ?"
        			, kv.get("cid"), kv.get("spid"), kv.get("ysid"), kv.get("cmid"));
        	//新增
        	Db.use(Const.SCMDB).update("insert into scm_buhuo_mdbhjgmx(id, mdid, spid, ysid, cmid,  skuid, ppid, jybhsl, sjbhsl, sjzt, mdqr) "
        			+ "values(?,?,?,?,?, ?,?,?,?,?,?) "
        			,YitIdHelper.nextId(), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid")
        			, rec.get("skuid"), rec.get("ppid"), 0, kv.get("sjbhsl"), 2, 1);

            return RetKit.ok("新增成功");
        }else {
            Integer qty = Db.use(Const.SCMDB).queryInt("select max(nvl(sjbhsl,0)) as sjbhsl from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=? "
                    , mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));
        	if(qty.equals(kv.getInt("sjbhsl"))) { //如果修改数量等于原实际补货数量，则不用修改
        		return RetKit.fail("未修改数量");
        	}

        	//修改
        	Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjgmx set sjbhsl=?, sjzt=1 where mdid=? and spid=? and ysid=? and cmid=? "
        			, kv.get("sjbhsl"), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        	//修改这个款色的备注
        	Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjgmx set bz=? where mdid=? and spid=? and ysid=? "
        			, kv.get("bz"), mdid, kv.get("spid"), kv.get("ysid") );

        	return RetKit.ok("修改成功");
        }
    }

    /**
     * 批量删除补货商品
     * @param delList
     * @param kv
     * @return
     */
    public RetKit deleteMdbhBatch(String delList, Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
        	return sftj;
        }

        JSONObject jsonObject = JSON.parseObject(delList);
        JSONArray idsArr = JSONArray.parseArray(jsonObject.getString("delList"));
		Object[][] paras = new Object[idsArr.size()][3];
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
			paras[i][0] = mdid;
			paras[i][1] = obj.get("spid");
			paras[i][2] = obj.get("ysid");
		}

		int[] cntArr = Db.use(Const.SCMDB).batch("update scm_buhuo_mdbhjgmx set mdsc=1, mdqr=0, sjzt=3 where mdid=? and spid=? and ysid=? ", paras, 100);

		//统计成功行数
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			if(cntArr[i]==-2 || cntArr[i]==1) { //oracle返回-2、sqlserver返回1，表示成功
				cntOk++;
			}
		}
		if(cntArr.length>0) {
			return RetKit.ok("成功删除 "+cntOk+" 条数据");
		}

		return RetKit.fail("批量删除失败");
    }

    /**
     * 门店提交
     * @param kv
     * @return
     */
    public RetKit commitBh(Kv kv) throws Exception {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
            return sftj;
        }
        //先修改补货主表为提交状态
        int update = Db.use(Const.SCMDB).templateByString("UPDATE scm_buhuo_mdbhjg a " // TODO
                + "set a.tjrq=SYSDATE, a.sftj=1, a.bz='#(bz)' "
                + "where a.mdid=#(qx_ssmd) "
                + "and EXISTS ( "
                + "SELECT 1 "
                + "FROM scm_buhuo_mdbhjgmx b "
                + "WHERE a.mdid = b.mdid AND a.ppid = b.ppid AND b.mdqr = 1)"
                + "#for(x: qx_pp) "
                + "  and ("
                + "    #for(x : qx_pp) "
                + "        a.ppid = '#(x)'"
                + "        #(for.last ? '' : 'or')"
                + "    #end "
                + "  ) "
                + "#end "
                + "", kv).update();

        //补货主表不存在则新增
    	List<Record> recList = Db.use(Const.SCMDB).templateByString("select a.mdid, a.ppid, min(a.createtime) as bhrq, sum(a.jybhsl) as jybhsl, sum(a.sjbhsl) as sjbhsl "
    			+ "from SCM_BUHUO_MDBHJGMX a "
        		+ "where a.mdid=#(qx_ssmd) "
        		+ "#for(x: qx_pp) "
        		+ "  and ("
        		+ "    #for(x : qx_pp)"
        		+ "        a.ppid = '#(x)'"
        		+ "        #(for.last ? '' : 'or')"
        		+ "    #end "
        		+ "  ) "
        		+ "#end "
        		+ " and a.mdid||'_'||a.ppid not in (select a.mdid||'_'||a.ppid as id from SCM_BUHUO_MDBHJG a where a.mdid=#(qx_ssmd) ) "
    			+ "group by a.mdid, a.ppid ", kv).find();
    	if(recList.size()>0) {
        	//批量新增
        	Object[][] paras = new Object[recList.size()][5];
    		for(int i=0;i<recList.size();i++) {
    			paras[i][0] = YitIdHelper.nextId();
    			paras[i][1] = recList.get(i).get("mdid");
    			paras[i][2] = recList.get(i).get("ppid");
    			paras[i][3] = recList.get(i).get("bhrq");
    			paras[i][4] = recList.get(i).get("bz"); //提交备注
    		}

    		Db.use(Const.SCMDB).batch("insert into scm_buhuo_mdbhjg(id, mdid, ppid, bhrq, bz) values(?,?,?,?,?) ", paras, 100);
    	}
		mdbhZhtjRq(kv);
        if (update > 0) {
            return RetKit.ok("提交成功");
        }
        return RetKit.fail("无数据提交");
    }

    private void mdbhZhtjRq(Kv kv) {
        List<Record> recList = Db.use(Const.SCMDB).templateByString("select a.mdid, a.ppid "
                + "from SCM_BUHUO_MDBHJGMX a "
                + "where a.mdid=#(qx_ssmd) and a.mdqr = 1"
                + "#for(x: qx_pp) "
                + "  and ("
                + "    #for(x : qx_pp)"
                + "        a.ppid = '#(x)'"
                + "        #(for.last ? '' : 'or')"
                + "    #end "
                + "  ) "
                + "#end "
                + "group by a.mdid, a.ppid ", kv).find();

        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
        String formattedDate = currentDate.format(formatter);
        Record first = Db.use(Const.SCMDB).findFirst("select to_char(min(createtime),'HH24:mi:ss') as bhsj from scm_buhuo_mdbhjgmx");
        String timeStr = "00:00:00"; // 获取时间字符串
        //判断最小时间不为空并赋值
        if (first.get("bhsj").toString() != null || !"".equals(first.get("bhsj").toString())){
            timeStr = first.get("bhsj").toString();
        }
        SimpleDateFormat inputFormat = new SimpleDateFormat("H:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");

        try {

            Date date = inputFormat.parse(timeStr);
            String formattedTimeStr = outputFormat.format(date);
            // 解析年月日字符串为 LocalDate 对象
            LocalDate localDate = LocalDate.parse(formattedDate);

            // 解析时分秒字符串为 LocalTime 对象
            LocalTime localTime = LocalTime.parse(formattedTimeStr);

            // 使用 DateTimeFormatter 定义输出格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 将 LocalDate 和 LocalTime 合并为 LocalDateTime 对象
            LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);

            // 格式化为指定格式的字符串
            String formattedDateTimeStr = localDateTime.format(outputFormatter);

            DateTimeFormatter frm = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime ldt = LocalDateTime.parse(formattedDateTimeStr, frm);

            // 将 LocalDateTime 转换为 Date
            Date dateZhuan = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
        if (recList.size() > 0) {
            //删除原有的
            Object[][] parList = new Object[recList.size()][2];
            for (int j = 0; j < recList.size(); j++) {
                parList[j][0] = recList.get(j).get("mdid");
                parList[j][1] = recList.get(j).get("ppid");
                Db.use(Const.SCMDB).batch("delete from scm_buhuo_bhtjzhrq where mdid = ? and ppid = ? ", parList, 100);

            }
            //批量新增
            Object[][] paras = new Object[recList.size()][4];
            for (int i = 0; i < recList.size(); i++) {
                paras[i][0] = YitIdHelper.nextId();
                paras[i][1] = recList.get(i).get("mdid");
                paras[i][2] = recList.get(i).get("ppid");
                paras[i][3] = dateZhuan;
            }
            Db.use(Const.SCMDB).batch("insert into scm_buhuo_bhtjzhrq(id, mdid, ppid, zhtjrq) values(?,?,?,?) ", paras, 100);
        }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消提交
     * @param kv
     * @return
     */
    public RetKit cancellation(Kv kv) throws Exception {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

    	//判断是否到了补货时间
    	RetKit retBhsj = buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}
        //判断补货数据是否审核中
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //修改补货主表为未提交状态
        Db.use(Const.SCMDB).templateByString("update scm_buhuo_mdbhjg set tjrq=null, sftj=0 "
        		+ "where mdid=#(qx_ssmd) "
        		+ "#for(x: qx_pp) "
        		+ "  and ("
        		+ "    #for(x : qx_pp)"
        		+ "        ppid = '#(x)'"
        		+ "        #(for.last ? '' : 'or')"
        		+ "    #end "
        		+ "  ) "
        		+ "#end "
        		+ "", kv).update();

		return RetKit.ok("取消提交成功");
    }

    /**
     * 门店确认某商品补货
     * @param kv
     * @return
     */
    public RetKit mdbhQrsp(Kv kv) throws Exception {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
        	return sftj;
        }

        //更新门店某款色的确认状态
        Db.use(Const.SCMDB).templateByString("update scm_buhuo_mdbhjgmx set mdqr=#(mdqr) "
        		+ "where mdid=#(qx_ssmd) "
        		+ " and spid=#(spid) and ysid=#(ysid) "
        		+ "", kv).update();

		return RetKit.ok("确认成功");
    }

    /**
     * 判断是否提交或审核
     */
    public RetKit detection(Kv kv) {
    	RetKit ret = RetKit.ok().set("sftj", "0").set("sfsh", "0");

    	//判断是否到了补货时间
    	RetKit retBhsj = buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}

    	//1判断是否生成单据了 TODO
        //2判断总部是否在审核中
    	RetKit retSh = shenHe(kv);
    	if(retSh.get("sfsh").equals("1")) {
    		return retSh;
    	}
    	//3判断门店是否已提交
    	RetKit retTj = tiJiao(kv);
    	if(retTj.get("sftj").equals("1")) {
    		return retTj;
    	}
        return ret;
    }

    /**
     * 判断是否到了补货时间
     */
    public RetKit buHuoShiJian(Kv kv) {
        kv.set("cid", getCid());

        try {
        	//获取当前时间戳
            Long dqsj = DateUtil.current(); //DateUtil.today(); //DateUtil.now();

            //获取设置的开始时间（格式为24小时制的时分秒，小时:分钟:秒）
            String ksbhsjStr = Db.use(Const.SCMDB).queryStr("select pz1 as ksbhsj from SCM_PZBH where bh='scm_buhuo_ksbhsj' ");
            //获取当前日期的年月日
            ksbhsjStr = DateUtil.today() + " " + ksbhsjStr;

            Long ksbhsj = DateUtil.parse(ksbhsjStr).getTime();

            if(dqsj < ksbhsj) {
            	return RetKit.fail("未到开始补货时间 "+ ksbhsjStr).set("sftj", "1");
            }
		} catch (Exception e) {
			e.printStackTrace();
			return RetKit.fail("判断开始补货时间异常:"+e.getMessage());
		}

        return RetKit.ok("可以开始补货了");
    }

    /**
     * 判断门店是否已提交
     */
    public RetKit tiJiao(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断是否提交
        int sftj = Db.use(Const.SCMDB).templateByString("select count(*) as cnt from scm_buhuo_mdbhjg a "
                		+ "where a.mdid=#(qx_ssmd) "
                		+ "#for(x: qx_pp) "
                		+ "  and ("
                		+ "    #for(x : qx_pp)"
                		+ "        a.ppid = '#(x)'"
                		+ "        #(for.last ? '' : 'or')"
                		+ "    #end "
                		+ "  ) "
                		+ "#end "
                		+ " and a.sftj=1 " //a.sftj=1 表示门店已提交
                		+ "", kv).queryInt();
        if(sftj>0) {
        	return RetKit.fail("数据已经提交过了").set("sftj", "1");
        }

        return RetKit.ok().set("sftj", "0").set("sfsh", "0");
    }

    /**
     * 判断总部是否在审核中
     */
    public RetKit shenHe(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断是否审核
        int sfsh = Db.use(Const.SCMDB).templateByString("select count(*) as cnt from scm_buhuo_mdbhjg a "
                		+ "where a.mdid=#(qx_ssmd) "
                		+ "#for(x: qx_pp) "
                		+ "  and ("
                		+ "    #for(x : qx_pp)"
                		+ "        a.ppid = '#(x)'"
                		+ "        #(for.last ? '' : 'or')"
                		+ "    #end "
                		+ "  ) "
                		+ "#end "
                		+ " and a.sfsh=1 " //a.sfsh=1 表示总部审核中
                		+ "", kv).queryInt();
        if(sfsh>0) {
        	return RetKit.fail("数据在审核中").set("sfsh", "1");
        }

        return RetKit.ok().set("sftj", "0").set("sfsh", "0");
    }

    /**
     * 获取门店补货进度、补货时间、补货数量
     * @param kv
     * @return
     */
    public Record getBhsj(Kv kv) {
    	String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //补货进度bhjd、补货日期bhrq、
        Record rec = Db.use(Const.SCMDB).templateByString("select case when max(a.sfsh)=1 then '审核中' when max(a.sftj)=1 then '已提交' else '未提交' end as bhjd "
        		+ ", min(a.bhrq) as bhrq "
        		+ "from scm_buhuo_mdbhjg a "
        		+ "where a.mdid=#(qx_ssmd) "
        		+ "#for(x: qx_pp) "
        		+ "  and ("
        		+ "    #for(x : qx_pp)"
        		+ "        a.ppid = '#(x)'"
        		+ "        #(for.last ? '' : 'or')"
        		+ "    #end "
        		+ "  ) "
        		+ "#end "
        		+ "", kv).findFirst();
        //实际补货数量、建议补货数量
        Record rec2 = Db.use(Const.SCMDB).templateByString("select sum(sjbhsl) as sjbhsl, sum(jybhsl) as jybhsl "
        		+ "from scm_buhuo_mdbhjgmx a "
        		+ "where a.mdid=#(qx_ssmd) "
        		+ "#for(x: qx_pp) "
        		+ "  and ("
        		+ "    #for(x : qx_pp)"
        		+ "        a.ppid = '#(x)'"
        		+ "        #(for.last ? '' : 'or')"
        		+ "    #end "
        		+ "  ) "
        		+ "#end "
        		+ "", kv).findFirst();

        rec.set("sjbhsl", rec2.get("sjbhsl"));
        rec.set("jybhsl", rec2.get("jybhsl"));

        return rec;
    }

    /**
     * 动态修改补货备注
     * @return
     */
    public List<Record> dtbhxgbz(){
        List<Record> rec = Db.use(Const.SCMDB).find("select pzmx2 from SCM_PZBHMX where mid in (select id from SCM_PZBH where bh = 'scm_buhuo_mdbhxgyy')");
        return rec;
    }

    /**
     * 获取门门店区域最后提交日期
     */
    public List<Record> getZhtjsj(Kv kv){
        String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        List<Record> records = Db.use(Const.SCMDB).templateByString("select md.storename as mdmc"
                + ", pp.attribname as ppmc, a.zhtjrq "
                + "from scm_buhuo_bhtjzhrq a "
                + "left join defstore md on a.mdid = md.id "
                + "left join defattrib pp on a.ppid = pp.id "
                + "where a.mdid=#(qx_ssmd)"
                + "#for(x: qx_pp) "
                + "  and ("
                + "    #for(x : qx_pp)"
                + "        a.ppid = '#(x)'"
                + "        #(for.last ? '' : 'or')"
                + "    #end "
                + "  ) "
                + "#end ",kv).find();
        return records;
    }

    /**
     * 新增停补商品
     * @param kv
     * @return
     */
    public RetKit insertTbsp(Kv kv){
        String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
            return sftj;
        }
        //更新门店某款色的确认状态
        Db.use(Const.SCMDB).templateByString("update scm_buhuo_mdbhjgmx set mdqr= 0 "
                + "where mdid=#(qx_ssmd) "
                + " and spid=#(spid) and ysid=#(ysid) "
                + "", kv).update();

        Integer cut = Db.use(Const.SCMDB).queryInt("select count(*) from scm_bhsp where mdid = ? and ysid = ? and spid = ? ",
                kv.get("qx_ssmd"), kv.get("ysid"), kv.get("spid"));
        int cnt = 0;
        if (cut > 0){
            cnt = Db.use(Const.SCMDB).update("update scm_bhsp set zt = 1 where mdid = ? and ysid = ? and spid = ? ",
                    kv.get("qx_ssmd"), kv.get("ysid"), kv.get("spid"));
        }else {
            cnt  = Db.use(Const.SCMDB).update("insert into scm_bhsp(id, mdid, ysid, spid, ppid, zt) values(?,?,?,?,?,?)",
                    YitIdHelper.nextId(), kv.get("qx_ssmd"), kv.get("ysid"), kv.get("spid"), kv.get("ppid"), 1);
        }
        if(cnt>0) {
            return RetKit.ok("停补商品成功");
        }
        return RetKit.fail("停补商品失败");
    }

    /**
     * 门店提交详情
     * @param kv
     * @return
     */
    public List<Record> mdtjxq(Kv kv){
        String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        return Db.use(Const.SCMDB).template("scmBuhuoMdbh.mdtjxq",kv).find();
    }

    /**
     * 门店表二保存
     */
    public RetKit xgbzClick(Kv kv){
        String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //判断补货数据是否已提交或审核中
        RetKit sftj = detection(kv);
        if(sftj.isFail()) {
            return sftj;
        }
        int update = Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjgmx set bz = ? " +
                "where mdid=? and spid = ? and ysid = ?", kv.get("bz"), kv.get("mdid"), kv.get("spid"), kv.get("ysid"));
        if (update > 0){
            return RetKit.ok("保存成功");
        }
        return RetKit.fail("保存失败");
    }


    /**
     *
     */
    public List<Record> selectBhmxLsjl(Kv kv){
        String mdid = getSsmdqx(kv.getStr("userCode"));
        kv.set("qx_ssmd", mdid); //用户所属门店权限
        kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoMdbh.selectBhmxLsjl",kv).find();

        return records;
    }
}
